<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search as IconSearch, Plus as IconPlus, View as IconView, Edit as IconEdit, Delete as IconDelete } from '@element-plus/icons-vue'
import warehouseApi from '@/api/warehouse'
import type { WarehouseInfo, CreateWarehouseParams } from '@/api/warehouse'

const tableData = ref<WarehouseInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchWarehouseName = ref('')

// 创建仓库对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('创建仓库')
const formRef = ref()
const formData = ref<CreateWarehouseParams>({
  warehouseName: '',
  location: '',
  capacity: 0,
  managerId: 0,
  status: 1
})

// 表单验证规则
const rules = {
  warehouseName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入仓库位置', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入仓库容量', trigger: 'blur' },
    { type: 'number', min: 0, message: '容量必须大于0', trigger: 'blur' }
  ],
  managerId: [
    { required: true, message: '请选择仓库管理员', trigger: 'change' }
  ]
}

// 仓库详情对话框相关
const detailDialogVisible = ref(false)
const detailDialogTitle = ref('仓库详情')
const warehouseDetail = ref<WarehouseInfo | null>(null)

// 编辑仓库对话框相关
const editDialogVisible = ref(false)
const editDialogTitle = ref('编辑仓库')
const editFormRef = ref()
const editFormData = ref<CreateWarehouseParams>({
  warehouseName: '',
  location: '',
  capacity: 0,
  managerId: 0,
  status: 1
})
const currentEditId = ref<number>(0)

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      warehouseName: searchWarehouseName.value.trim() || undefined
    }
    const res = await warehouseApi.getWarehouseList(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取仓库列表失败')
  }
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getWarehouseList()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getWarehouseList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getWarehouseList()
}

// 打开创建仓库对话框
const handleCreate = () => {
  dialogVisible.value = true
  formData.value = {
    warehouseName: '',
    location: '',
    capacity: 0,
    managerId: 0,
    status: 1
  }
}

// 提交创建仓库表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await warehouseApi.createWarehouse(formData.value)
        ElMessage.success('创建仓库成功')
        dialogVisible.value = false
        getWarehouseList() // 刷新列表
      } catch (error) {
        ElMessage.error('创建仓库失败')
      }
    }
  })
}

// 取消创建
const handleCancel = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 查看仓库详情
const handleViewDetail = async (row: WarehouseInfo) => {
  try {
    const res = await warehouseApi.getWarehouseById(row.warehouseId)
    warehouseDetail.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取仓库详情失败')
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  warehouseDetail.value = null
}

// 打开编辑仓库对话框
const handleEdit = async (row: WarehouseInfo) => {
  try {
    const res = await warehouseApi.getWarehouseById(row.warehouseId)
    editFormData.value = {
      warehouseName: res.data.warehouseName,
      location: res.data.location,
      capacity: res.data.capacity,
      managerId: res.data.managerId,
      status: res.data.status ? 1 : 0
    }
    currentEditId.value = row.warehouseId
    editDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取仓库信息失败')
  }
}

// 提交编辑仓库表单
const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await warehouseApi.updateWarehouse(currentEditId.value, editFormData.value)
        ElMessage.success('更新仓库成功')
        editDialogVisible.value = false
        getWarehouseList() // 刷新列表
      } catch (error) {
        ElMessage.error('更新仓库失败')
      }
    }
  })
}

// 取消编辑
const handleEditCancel = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
}

// 删除仓库
const handleDelete = async (row: WarehouseInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除仓库"${row.warehouseName}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await warehouseApi.deleteWarehouse(row.warehouseId)
    ElMessage.success('删除仓库成功')
    getWarehouseList() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除仓库失败')
    }
  }
}

// 初始化加载
onMounted(() => {
  getWarehouseList()
})
</script>

<template>
  <div class="warehouse-list-container">
    <div class="search-bar">
      <el-input
        v-model="searchWarehouseName"
        placeholder="请输入仓库名称"
        class="search-input"
        :prefix-icon="IconSearch"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" :icon="IconPlus" @click="handleCreate">创建仓库</el-button>
    </div>

    <!-- 创建仓库对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleCancel"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="formData.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库位置" prop="location">
          <el-input v-model="formData.location" placeholder="请输入仓库位置" />
        </el-form-item>
        <el-form-item label="仓库容量" prop="capacity">
          <el-input-number
            v-model="formData.capacity"
            :min="0"
            :precision="2"
            :step="100"
            placeholder="请输入仓库容量"
          />
        </el-form-item>
        <el-form-item label="管理员" prop="managerId">
          <el-select v-model="formData.managerId" placeholder="请选择管理员">
            <el-option label="管理员1" :value="1" />
            <el-option label="管理员2" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-table :data="tableData" border style="width: 100%" class="warehouse-table">
      <el-table-column prop="warehouseId" label="仓库ID" width="100" />
      <el-table-column prop="warehouseName" label="仓库名称" width="180" />
      <el-table-column prop="location" label="位置" width="180" />
      <el-table-column prop="capacity" label="容量" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="管理员信息" width="180">
        <template #default="{ row }">
          <div>{{ row.manager?.realName || '-' }} ({{ row.manager?.username || '-' }})</div>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            :icon="IconView"
            circle
            @click="handleViewDetail(row)"
          />
          <el-button
            type="warning"
            :icon="IconEdit"
            circle
            @click="handleEdit(row)"
          />
          <el-button
            type="danger"
            :icon="IconDelete"
            circle
            @click="handleDelete(row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 仓库详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="detailDialogTitle"
      width="600px"
      @close="handleCloseDetail"
    >
      <el-descriptions
        v-if="warehouseDetail"
        :column="2"
        border
      >
        <el-descriptions-item label="仓库ID">
          {{ warehouseDetail.warehouseId }}
        </el-descriptions-item>
        <el-descriptions-item label="仓库名称">
          {{ warehouseDetail.warehouseName }}
        </el-descriptions-item>
        <el-descriptions-item label="位置">
          {{ warehouseDetail.location }}
        </el-descriptions-item>
        <el-descriptions-item label="容量">
          {{ warehouseDetail.capacity }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="warehouseDetail.status ? 'success' : 'danger'">
            {{ warehouseDetail.status ? '正常' : '停用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="管理员">
          {{ warehouseDetail.manager?.realName || '-' }} ({{ warehouseDetail.manager?.username || '-' }})
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ warehouseDetail.createdAt }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ warehouseDetail.updatedAt }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button link @click="handleCloseDetail">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑仓库对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editDialogTitle"
      width="500px"
      @close="handleEditCancel"
    >
      <el-form
        ref="editFormRef"
        :model="editFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="editFormData.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库位置" prop="location">
          <el-input v-model="editFormData.location" placeholder="请输入仓库位置" />
        </el-form-item>
        <el-form-item label="仓库容量" prop="capacity">
          <el-input-number
            v-model="editFormData.capacity"
            :min="0"
            :precision="2"
            :step="100"
            placeholder="请输入仓库容量"
          />
        </el-form-item>
        <el-form-item label="管理员" prop="managerId">
          <el-select v-model="editFormData.managerId" placeholder="请选择管理员">
            <el-option label="管理员1" :value="1" />
            <el-option label="管理员2" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editFormData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button link @click="handleEditCancel">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :disabled="!total"
      />
    </div>
  </div>
</template>

<style scoped>
.warehouse-list-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.warehouse-table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-descriptions {
  margin: 20px 0;
}

.el-descriptions-item {
  padding: 12px 20px;
}

.el-button + .el-button {
  margin-left: 8px;
}

.el-button.is-circle {
  padding: 6px;
}
</style>